有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

继承类的java保护静态成员

我有几个类都继承了相同的基类,需要有一个静态属性,在启动时在函数中初始化。我是这样实现的:

public abstract class Base {
    protected static Model model;
}

public class Inherited extends Base {
    static {
        model = initializationFunction();
    }
}
public class OtherInherited extends Base {
    static {
        model = otherInitializationFunction();
    }
}
// Example of use
Base[] inheriteds = new Base[] { new Inherited(), new OtherInherited() };
for (int i = 0; i < inheriteds.length; i++)  {
     doStuff(inheriteds[i]).model; // This will always use the same model (last defined)
}

因此,该类在开始时初始化静态成员。但它似乎为整个基类设置了model的值,因此所有类实际上都有相同的模型

我需要model是静态的,因为它只需要在每个子类中存在一次。我的问题是,如何在确保在父类中定义一个静态模型的同时,让每个子类都有一个静态模型(因此,如果一个类没有定义它,它将在父类中定义)

继承类中受保护的静态成员的预期行为是什么?我应该如何让每个类的这个成员的版本保持静态(我不希望每个实例都重复)


共 (2) 个答案

  1. # 1 楼答案

    正如其他答案所建议的,静态成员的范围是在类级别,而不是在对象级别,简而言之,它们根本不是继承层次结构的一部分。静态成员的类名只是一个额外的命名空间限定符。下面是关于静态关键字的一个很好的概要:http://mindprod.com/jgloss/static.html

    至于解决你的问题,我尝试了一下,同时仍然使用静态成员。如果你真的必须让一个子类的每个实例共享同一个模型实例,同时保持某种与基类的接口兼容性,那么考虑做如下的事情:

    public abstract class Base {
        public abstract Model getModel();
    }
    
    public class Inherited extends Base {
        static private Model model = initializationFunction();
    
        public Model getModel() {
            return model;
        }
    }
    
    public class OtherInherited extends Base {
        static private Model model = otherInitializationFunction();
    
        public Model getModel() {
            return model;
        }
    }
    

    这里涉及静态成员的事实对界面是隐藏的,这是一个巨大的胜利。如果不使用静态成员就可以解决这个问题,那么这里的类层次结构的客户端将不会受到影响,因为访问模型根本不会公开使用静态成员的实现细节

  2. # 2 楼答案

    My problem is how to have one static model per subclass, while still ensuring it is defined in the parent class (so if a class doesn't define it, it is defined in the parent class).

    不可能,因为静态成员和多态性、继承不能同时进行